package cn.wujiangbo.controller;

import cn.hutool.core.io.FileUtil;
import cn.wujiangbo.annotation.IgnoreAuth;
import cn.wujiangbo.controller.base.BaseController;
import cn.wujiangbo.result.JSONResult;
import cn.wujiangbo.service.system.impl.FileServiceOssImpl;
import cn.wujiangbo.util.MyTools;
import cn.wujiangbo.vo.UploadFileVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * <p>文件处理类</p>
 *
 * @Author 波波老师(weixin : javabobo0513)
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    @Resource
    private FileServiceOssImpl fileService;

    /**
     * 上传文件
     *
     * @param multipartFile 文件对象
     */
    @IgnoreAuth
    @PostMapping("/uploadImageCommon")
    public JSONResult uploadTanhuapingju(@RequestParam("fileName") MultipartFile multipartFile) {
        UploadFileVo uploadFileVo = fileService.uploadFile(multipartFile, "EasyJavaTemplate/userImage");
        return JSONResult.success(uploadFileVo);
    }

    /**
     * 文件下载
     */
    @IgnoreAuth
    @GetMapping("/download/{fileFullName}")
    public void downloadFile(@PathVariable("fileFullName") String fileFullName,
                             HttpServletResponse httpServletResponse) throws IOException {
        String fileUploadPath = MyTools.getFileUploadPath(fileFullName);
        byte[] bytes = FileUtil.readBytes(fileUploadPath);
        httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileFullName, "UTF-8"));  // 附件下载
        OutputStream os = httpServletResponse.getOutputStream();
        os.write(bytes);
        os.flush();
        os.close();
    }
}
